package com.zhuss.core.processor;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.zhuss.bean.bo.core.book.SearchBookBo;
import com.zhuss.bean.vo.core.book.DetailBookVo;
import com.zhuss.bean.vo.core.book.ListBookVo;
import com.zhuss.bean.vo.core.company.DetailCompanyVo;
import com.zhuss.common.ListVo;
import com.zhuss.common.PageVo;
import com.zhuss.core.db.dao.ext.BookDao;
import com.zhuss.core.db.entity.Book;
import com.zhuss.enums.StartStopEnum;
import com.zhuss.exception.AabException;
import com.zhuss.exception.ExceptionCode;


/**
 * 查询Book processor
 * @Author: zhushanshuo
 * @Date: 2019/9/24 19:54
 */
@Component("bookRead")
public class BookRead {
	
	@Autowired
	private BookDao bookDao;
	
	@Autowired
	@Qualifier("companyRead")
	private CompanyRead companyRead;
	
	/**
	 * Book
	 * @return
	 */
	public Object listBook() {
		List<Book> bookList = bookDao.listAll();
		List<ListVo> result = new ArrayList<>();
		transferList(bookList, result);
		return result;
	}
	
	/**
	 * Book list
	 * @return
	 */
	public Object listAll() {
		List<Book> bookList = bookDao.listAll();
		return bookList;
	}
	
	private void transferList(List<Book> bookList, List<ListVo> result) {
		for (Book item : bookList) {
			ListVo vo = new ListVo();
			vo.setKey(item.getBookId());
			vo.setLabel(item.getName());
			result.add(vo);
		}
		
	}

	/**
	 * Book列表
	 * @param bo
	 * @return
	 * @throws AabException 
	 */
	public Object list(SearchBookBo bo) throws AabException {
		PageVo<ListBookVo> result = new PageVo<ListBookVo>();
        result.setPageNum(bo.getPageNum());
        result.setPageSize(bo.getPageSize());
        result.setItems(transfer(bookDao.list(bo)));
        result.setTotal(bookDao.countList(bo));
		return result;
	}
	
	private List<ListBookVo> transfer(List<ListBookVo> list) throws AabException {
		for (ListBookVo item : list) {
			DetailCompanyVo company = (DetailCompanyVo) companyRead.detail(item.getCompanyId());
			item.setCompanyName(company.getName());
		}
		return list;
	}



	/**
	 * Book详情
	 * @param bookId
	 * @return
	 * @throws AabException
	 */
	public Object detail(Long bookId) throws AabException {
		Object result = bookDao.detail(bookId);
		if (result == null) {
			throw new AabException(ExceptionCode.数据不存在);
		}
		DetailBookVo vo = (DetailBookVo) result;
		if (vo.getCompanyId() != null && vo.getCompanyId() > 0l) {
			vo.setCompanyName(((DetailCompanyVo) companyRead.detail(vo.getCompanyId())).getName());
		}
		return result;
	}
	
	public List<Long> listByName(String name) {
		List<Long> result = bookDao.listByName(name, StartStopEnum.启用.key());
		return result;
	}
	
	

}
